<?php
/**
 * This file is part of manage.
 * Author: tangzhou
 * Date: 2016/7/4
 * Time: 9:45
 * File: Vcc8016070401Controller.php
 */

namespace Ivr\HttpBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * Class Vcc8016070401Controller
 * @package Ivr\HttpBundle\Controller
 */
class Vcc8016070401Controller extends Controller
{
    const API_URL_DEV = 'https://backend.sandbox.yongche.org/api/openapi.php';
    const API_URL_PROD = 'https://platform.yongche.com/api/openapi.php';
    const API_SECRET = '427e0c4532eca20a91f27a3d542caa31';
    const VCC_ID = 2000133;

    /**
     * 调用易道用车
     * @param Request $request
     * @return JsonResponse
     */
    public function vipAction(Request $request)
    {
        $userId = $request->get('user_id', '');
        $callerPhone = $request->get('caller', '');
        $env = $request->get('env', 'dev');
        if (empty($userId) && empty($callerPhone)) {
            return new JsonResponse(array(
                'result' => 'failure',
            ));
        }
        //判断是不是BD
        $isBd = $this->checkVip(self::VCC_ID, $callerPhone, 3);//BD 为3
        if ($isBd) {
            return new JsonResponse(array(
                'result' => 'success',
                'data' => array(
                    'is_vip' => 100,
                ),
            ));
        }
        $params = array();
        if (!empty($userId)) {
            $params['user_id'] = $userId;
        } else {
            $params['cellphone'] = $callerPhone;
        }

        $vccId = self::VCC_ID;
        $isVip = $this->checkVip($vccId, $callerPhone);
        if ($isVip) {
            return new JsonResponse(array(
                'result' => 'success',
                'data' => array(
                    'is_vip' => 1,
                ),
            ));
        }

        $params['module'] = 'member';
        $params['method'] = 'getInfo';
        $params['ts'] = time();
        $params['sign'] = $this->getSign($params);
        $this->get("logger")->info("发送params".json_encode($params));
        $response = $this->getResponse($env, $params);
        $responseArray = json_decode($response, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            $this->get("logger")->error(sprintf('8016070401 VIP响应结果为非json格式，结果为【%s】.', $response));

            return new JsonResponse(array(
                'result' => 'failure',
            ));
        }
        $result = isset($responseArray['ret_code']) ? $responseArray['ret_code'] : 0;
        if ($result == 200 && isset($responseArray['data']['is_vip'])) {
            return new JsonResponse(array(
                'result' => 'success',
                'data' => array(
                    'is_vip' => $responseArray['data']['is_vip'] ? 1 : 0,
                ),
            ));
        } else {
            $this->get("logger")->info(sprintf('8016070401获取失败%s', $response));

            return new JsonResponse(array(
                'result' => 'failure',
            ));
        }
    }

    /**
     * 司机端vip 判断
     * @param Request $request
     * @return JsonResponse
     */
    public function driverIsVipAction(Request $request)
    {
        $callerPhone = $request->get('caller', '');
        if (empty($callerPhone)) {
            return new JsonResponse(array(
                'result' => 'failure',
            ));
        }

        // 判断当前时间
        $nowHour = intval(date('H'));
        $nowMinute = intval(date('i'));
        $nowSecond = intval(date('s'));
        if ($nowHour < 9 || $nowHour > 22 || ($nowHour == 22 && ($nowSecond > 0 || $nowMinute > 0))) {
            return new JsonResponse(array(
                'result' => 'success',
                'data' => array(
                    'is_vip' => 0,
                ),
            ));
        }

        $isVip = $this->checkVip(self::VCC_ID, $callerPhone, 2);

        return new JsonResponse(array(
            'result' => 'success',
            'data' => array(
                'is_vip' => $isVip ? 1 : 0,
            ),
        ));
    }

    /**
     * @param $vccId
     * @param $phone
     * @param $type
     * @return bool
     * 验证是否是vip用户
     */
    protected function checkVip($vccId, $phone, $type = 1)
    {
        $conn = $this->get('doctrine.dbal.default_connection');
        $res = $conn->fetchAll(
            "select id from cc_vip_phone where vcc_id = :vcc_id and phone = :phone AND pho_type = :pho_type limit 1",
            array(
                'vcc_id' => $vccId,
                'phone' => $phone,
                'pho_type' => $type,
            )
        );
        if (!empty($res)) {
            return true;
        }

        return false;
    }
    /**
     * 短信接口
     * @param Request $request
     * @return JsonResponse
     */
    public function smsAction(Request $request)
    {
        $callerPhone = $request->get('caller', '');
        $msg = $request->get('msg', '');
        $flag = $request->get('flag', false);
        $env = $request->get('env', 'dev');

        if (empty($callerPhone) || empty($msg) || !$this->checkPhoneIsMobile($callerPhone)) {
            return new JsonResponse(array(
                'result' => 'failure',
            ));
        }
        $params['module'] = 'sms';
        $params['method'] = 'send';
        $params['phone'] = $callerPhone;
        $params['msg'] = $msg;
        $params['ts'] = time();
        if ($flag !== false) {
            $params['flag'] = $flag;
        }
        $params['sign'] = $this->getSign($params);

        $this->get("logger")->info("8016070401SMS发送params".json_encode($params));
        $response = $this->getResponse($env, $params);
        $responseArray = json_decode($response, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            $this->get("logger")->error(sprintf('8016070401 SMS响应结果为非json格式，结果为【%s】.', $response));

            return new JsonResponse(array(
                'result' => 'failure',
            ));
        }
        $result = isset($responseArray['ret_code']) ? $responseArray['ret_code'] : 0;
        if ($result == 200 && isset($responseArray['data'])) {
            return new JsonResponse(array(
                'result' => 'success',
                'data' => array(
                    'res' => $responseArray['data'],
                ),
            ));
        } else {
            $this->get("logger")->info(sprintf('8016070401 SMS获取失败%s', $response));

            return new JsonResponse(array(
                'result' => 'failure',
            ));
        }

    }

    /**
     * 获取sign
     * @param $params
     * @return string
     */
    private function getSign($params)
    {
        ksort($params);
        $requestPath = '/api/openapi.php';
        foreach ($params as $k => $v) {
            $requestPath.=$k.'='.$v.'&';
        }
        $requestPath= rtrim($requestPath, '&');
        $sign = sha1($requestPath.self::API_SECRET);

        return $sign;
    }

    /**
     * 发送请求
     * @param $env
     * @param $params
     * @return mixed
     */
    private function getResponse($env, $params)
    {
        $url = $env == 'prod' ? self::API_URL_PROD : self::API_URL_DEV;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 2);
        $response = curl_exec($ch);
        $this->get("logger")->info(
            sprintf('8016070401 url【%s】params【%s】response【%s】.', $url, json_encode($params), $response)
        );

        return $response;
    }

    /**
     * 检查电话号码是否是移动电话
     *
     * @param string $phone 电话号码
     * @return bool
     */
    private function checkPhoneIsMobile($phone)
    {
        if (empty($phone)) {
            return false;
        }

        if (preg_match('/^(\+)?(86)?(0)?1[3-9]\d{9}$/', $phone)) {
            return true;
        } else {
            return false;
        }
    }
}
